/**
 * Echarts柱状图
 * @author 木人心
 * @version 1.0.1
 */
import { BarSeriesOption, EChartsOption } from 'echarts'
import { ObjectUtil } from '@utils/object-util'
import { CartesianSystemStyle, getCartesianSystemStyle } from './cartesianSystem'
import { ChartColor } from '../type'
import { EChartsUtil } from '../utils'

/**
 * 获取柱状图基本样式
 */
function getBarStyleBase (): EChartsOption {
  const option = getCartesianSystemStyle()
  option.tooltip = {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  }
  // (option.xAxis as any).boundaryGap = false
  return option
}

/**
 * 获取一条柱图
 * @param config
 */
function getBarStyle (config: {
  color: string,
  name: string,
  unit?: string,
  area?: boolean,
  areaColor?: ChartColor,
  direction?: 'horizontal' | 'vertical'
}) {
  const lineStyle = new BarStyle()
  lineStyle.addSeries(getBarSeries(config))
  lineStyle.setYAxis({ name: config.unit })
  return lineStyle
}

/**
 * 获取多条柱图
 * @param config
 */
function getBarsStyle (config: {
  colors: string[],
  names: string[],
  unit?: string,
  area?: boolean,
  areaColors?: ChartColor[],
  direction?: 'horizontal' | 'vertical'
}) {
  if (!config.areaColors) config.areaColors = []
  const lineStyle = new BarStyle()
  lineStyle.setYAxis({ name: config.unit })
  for (let i = 0, len = config.names.length; i < len; i++) {
    lineStyle.addSeries(getBarSeries({
      color: config?.colors[i],
      name: config?.names[i],
      area: config.area,
      areaColor: config?.areaColors[i],
      direction: config.direction
    }))
  }
  return lineStyle
}

/**
 * 获取一个柱图系列
 * @param config
 * @param option
 */
function getBarSeries (config: {
  name: string,
  color?: string,
  area?: boolean,
  areaColor?: ChartColor,
  direction?: 'horizontal' | 'vertical'
}, option?: BarSeriesOption): BarSeriesOption {
  const _option = { type: 'bar', name: config.name } as any
  if ((config.area || ObjectUtil.isString(config.areaColor)) && config.color) {
    _option.itemStyle = {
      color: EChartsUtil.getLinearGradient(config.color, config.areaColor as string, config.direction)
    }
  } else {
    _option.itemStyle = { color: config.color }
  }
  if (option) ObjectUtil.assignDeep(_option, option)
  return _option
}

class BarStyle extends CartesianSystemStyle {
  currentOption: EChartsOption = getBarStyleBase()

  /**
   * 切换为垂直显示（切换横纵轴）
   */
  toVertical () {
    const yName = this.currentOption.yAxis[0].name
    const xName = (this.currentOption.xAxis as any).name
    this.setXAxis({ type: 'value', name: yName }).setYAxis({ type: 'category', name: xName })
    return this
  }
}

export { getBarStyle, getBarSeries, getBarsStyle }
